<!-- 农事农服 -->
<template>
  <div>
    <CommonSearch @search="query" @reset="reset">
      <el-col :span="8">
        <el-form-item label="标题">
          <el-input
            v-model="queryParams.condition.title"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="所属分类">
          <QueryCategoryTree v-model="queryParams.condition.catgory" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="queryParams.condition.searchTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%; height: 33px"
            @change="(date) => timeChange(date, queryParams.condition)"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="是否推荐">
          <DictSelect
            v-model="queryParams.condition.recommend"
            :defaultOptions="options.recommend"
            placeholder="请选择状态"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="上架状态">
          <DictSelect
            v-model="queryParams.condition.pushStatus"
            :defaultOptions="options.pushStatus"
            placeholder="请选择状态"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </CommonSearch>

    <el-row class="cardMiniBar">
      <el-col :span="24">
        <div class="fr">
          <el-button type="primary" @click="add" size="small">新增</el-button>
          <el-button type="primary" @click="onExport" size="small"
            >导出</el-button
          >
          <el-button @click="batchPublish" size="small">批量上架</el-button>
          <el-button @click="revokeBatchPublish" size="small"
            >批量撤销上架</el-button
          >
          <el-button @click="batchRecommended" size="small">批量推荐</el-button>
          <el-button @click="revokeBatchRecommended" size="small"
            >批量取消推荐</el-button
          >
        </div>
      </el-col>
    </el-row>

    <div class="cardBody">
      <edu-table
        ref="mainTable"
        :data="tableList"
        :pageSize="queryParams.pageSize"
        :pageNum="queryParams.pageNum"
        :total="queryParams.total"
        @page-change="handleCurrentChange"
        :order="true"
        :selection="true"
      >
        <el-table-column label="标题" prop="title" />
        <el-table-column label="预算" prop="price" :formatter="rounding" />
        <el-table-column label="所属分类" prop="catgoryName" />
        <!-- <el-table-column label="用户名称" prop="providerName" /> -->
        <!-- <el-table-column label="所属分类" prop="catgoryName" />
        <el-table-column label="所属品类" prop="produceCategoryId" /> -->
        <el-table-column label="发布时间" prop="pubdate" width="160" />
        <el-table-column label="是否推荐" prop="recommend">
          <template slot-scope="scope">
            {{ renderOption(scope.row.recommend, "recommend") }}
          </template>
        </el-table-column>
        <el-table-column label="上架状态" prop="pushStatus">
          <template slot-scope="scope">
            {{ renderOption(scope.row.pushStatus, "pushStatus") }}
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="220px">
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="scope.row.pushStatus == 2"
              @click="view(scope.row)"
              size="small"
            >
              查看
            </el-button>
            <el-button
              type="text"
              v-if="scope.row.pushStatus == 2"
              @click="edit(scope.row)"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              v-if="scope.row.pushStatus == 2"
              @click="handlerDelete(scope.row)"
              size="small"
            >
              删除
            </el-button>

            <el-button
              type="text"
              v-if="scope.row.pushStatus == 2"
              @click="publish(scope.row)"
              size="small"
              >上架</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.pushStatus == 1"
              @click="revokePublish(scope.row)"
              size="small"
              >取消上架</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.recommend == 2"
              @click="recommended(scope.row)"
              size="small"
              >推荐</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.recommend == 1"
              @click="revokeRecommended(scope.row)"
              size="small"
              >取消推荐</el-button
            >
          </template>
        </el-table-column>
      </edu-table>
    </div>

    <edu-dialog
      :title.sync="dialogConfig.title"
      :visible.sync="dialogConfig.showDialog"
      @close="handleDialogClose"
      width="70%"
    >
      <el-form
        ref="dialogForm"
        :model="dialogConfig.formData"
        :rules="dialogConfig.action === 'view' ? {} : dialogConfig.rules"
        label-width="230px"
        :disabled="dialogConfig.action === 'view'"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="dialogConfig.formData.title" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预算" prop="price">
              <el-input v-model="dialogConfig.formData.price" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="catgory">
              <QueryCategoryTree v-model="dialogConfig.formData.catgory" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="dialogConfig.formData.author" clearable />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="24">
            <el-form-item label="摘要" prop="resume">
              <el-input v-model="dialogConfig.formData.resume" clearable />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="微信号码" prop="weChat">
              <el-input v-model="dialogConfig.formData.weChat" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="dialogConfig.formData.phone" clearable />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="用户名称" prop="providerName">
              <el-input
                v-model="dialogConfig.formData.providerName"
                clearable
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="封面" prop="image">
              <Upload v-model="dialogConfig.formData.image" ref="uploadComp" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="dialogConfig.formData.description"
                type="textarea"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="buttons" v-if="dialogConfig.action !== 'view'">
        <template>
          <el-button @click="closeDialog(dialogConfig)"> 取消 </el-button>
          <el-button type="primary" @click="handlerSubmit"> 提交 </el-button>
        </template>
      </span>
      <span slot="buttons" v-else>
        <template>
          <el-button @click="closeDialog(dialogConfig)">返回</el-button>
        </template>
      </span>
    </edu-dialog>
  </div>
</template>

<script>
import utils from "@/utils";
import mixins from "@/mixins";
import {
  pageFarmSeek,
  deleteFarmSeek,
  pushFarmSeek,
  unpushFarmSeek,
  recommendFarmSeek,
  unrecommendFarmSeek,
  detailFarmSeek,
  addFarmSeek,
  updateFarmSeek,
  exportFarmSeek,
} from "@/api/service";

const formData = {};
export default {
  mixins: [mixins],
  data() {
    return {
      queryParams: {
        condition: {
          searchBeginTime: "",
          searchEndTime: "",
          catgory: "",
          pushStatus: "",
          recommend: "",
          title: "",
        },
        pageNum: 1,
        pageSize: 10,
      },
      tableList: [],
      dialogConfig: {
        title: "",
        showDialog: false,
        action: "add",
        formData: {},
        rules: {
          title: [
            {
              required: true,
              validator: this.checkTitle,
              trigger: "blur",
            },
          ],
          price: [
            {
              required: true,
              validator: this.checkPrice,
              trigger: "blur",
            },
          ],
          catgory: [
            {
              required: true,
              message: "此项必填！",
              trigger: "blur",
            },
          ],
          phone: [
            {
              required: true,
              validator: this.checkPhone,
              trigger: "blur",
            },
          ],
        },
      },
      options: {},
    };
  },
  created() {
    this.initOptions();
  },
  methods: {
    checkTitle(rule, value, callback) {
      if (!value) {
        callback(new Error("此项必填！"));
      } else if (value.length > 50) {
        callback(new Error("超出字数限制50"));
      } else {
        callback();
      }
    },
    checkPrice(rule, value, callback) {
      let regExp = /^\d+(.\d{1,2})?$/;
      if (!value) {
        callback(new Error("此项必填！"));
      } else if (!regExp.test(value)) {
        callback(new Error("请输入正数且保留小数点两位以内"));
      } else {
        callback();
      }
    },
    checkPhone(rule, value, callback) {
      let regExp = /^1[23456789]\d{9}$/;
      if (!value) {
        callback(new Error("此项必填！"));
      } else if (!regExp.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    },
    async initOptions() {
      this.query();
    },
    // 查询
    async query() {
      let { returnObj } = await pageFarmSeek(this.queryParams);
      this.tableList = returnObj.list;
      this.queryParams.total = returnObj.total;
      this.queryParams.pageSize = returnObj.pageSize;
    },
    // 重置
    reset() {
      for (var key in this.queryParams.condition) {
        this.queryParams.condition[key] = "";
      }
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;

      this.query();
    },
    // 分页
    handleCurrentChange(row) {
      this.queryParams.pageSize = row.pageSize;
      this.queryParams.pageNum = row.pageNum;

      this.query();
    },
    closeDialog(dialog) {
      dialog.showDialog = false;
      this.$refs["dialogForm"].resetFields();
    },
    openDialog(dialog) {
      dialog.showDialog = true;
    },
    // 新增
    add() {
      this.dialogConfig.title = "新增";
      this.dialogConfig.action = "add";
      this.dialogConfig.formData = utils.clone(formData);

      this.openDialog(this.dialogConfig);
      this.$nextTick(() => {
        this.$refs.uploadComp.init();
      });
    },
    // 修改
    async edit(row) {
      this.dialogConfig.title = "编辑";
      this.dialogConfig.action = "edit";

      let { returnObj } = await detailFarmSeek(row.id);
      this.dialogConfig.formData = utils.clone(returnObj);
      this.$nextTick(() => {
        this.$refs.uploadComp.init();
      });

      this.openDialog(this.dialogConfig);
    },
    // 保存提交
    handlerSubmit() {
      let params = {
        ...this.dialogConfig.formData,
      };
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          if (this.dialogConfig.action == "add") {
            addFarmSeek(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          } else {
            updateFarmSeek(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          }
        }
      });
    },
    // 查看
    async view(row) {
      console.log(row);
      this.dialogConfig.title = "查看";
      this.dialogConfig.action = "view";
      //  this.dialogConfig.formData = utils.clone(row);
      let { returnObj } = await detailFarmSeek(row.id);
      this.dialogConfig.formData = utils.clone(returnObj);
      this.$nextTick(() => {
        this.$refs.uploadComp.init();
      });
      this.openDialog(this.dialogConfig);
    },
    // 关闭弹框
    handleDialogClose() {
      this.closeDialog(this.dialogConfig);
    },
    // 上架
    async publish(row) {
      this.$confirm(`确认上架?`).then(() => {
        pushFarmSeek([row.id]).then((res) => {
          this.$message({
            type: "success",
            message: "成功",
          });
          this.query();
        });
      });
    },
    // 取消上架
    async revokePublish(row) {
      unpushFarmSeek([row.id]).then((res) => {
        this.$message({
          type: "success",
          message: "成功",
        });
        this.query();
      });
    },
    // 批量上架
    async batchPublish() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量上架?`).then(() => {
        pushFarmSeek(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量上架成功",
          });
          this.query();
        });
      });
    },
    // 批量取消上架
    async revokeBatchPublish() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量取消上架?`).then(() => {
        unpushFarmSeek(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量取消上架成功",
          });
          this.query();
        });
      });
    },

    // 推荐
    async recommended(row) {
      this.$confirm(`确认推荐?`).then(() => {
        recommendFarmSeek([row.id]).then((res) => {
          this.$message({
            type: "success",
            message: "成功",
          });
          this.query();
        });
      });
    },
    // 取消推荐
    async revokeRecommended(row) {
      unrecommendFarmSeek([row.id]).then((res) => {
        this.$message({
          type: "success",
          message: "成功",
        });
        this.query();
      });
    },
    // 批量推荐
    async batchRecommended() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量推荐?`).then(() => {
        recommendFarmSeek(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量推荐成功",
          });
          this.query();
        });
      });
    },
    // 批量取消推荐
    async revokeBatchRecommended() {
      let list = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      if (!list || list.length == 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }
      this.$confirm(`确认批量取消推荐?`).then(() => {
        unrecommendFarmSeek(list).then((res) => {
          this.$message({
            type: "success",
            message: "批量取消推荐成功",
          });
          this.query();
        });
      });
    },
    // 删除
    async handlerDelete(row) {
      let idField = "id";
      if (row && row[idField]) {
        this.batchDelete(deleteFarmSeek, idField, [row[idField]]);
      } else {
        this.batchDelete(deleteFarmSeek, idField);
      }
    },
    onExport() {
      let selectedIds = this.$refs.mainTable.getCheckData().map((item) => {
        return item.id;
      });

      // if (!selectedIds || selectedIds.length == 0) {
      //   this.$message({
      //     type: "warning",
      //     message: "请勾选要导出的数据",
      //   });
      //   return;
      // }
      exportFarmSeek({
        selectedIds,
        condition: {
          ...this.queryParams.condition,
        },
      }).then((res) => {
        utils.downloadFile(res);
      });
    },
    rounding(row, column) {
      return parseFloat(row[column.property]).toFixed(2);
    },
  },
};
</script>

<style lang="scss" scoped></style>
